package com.hntest.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hntest.entity.LoginInfo;
import com.hntest.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

@Controller("loginController")
public class LoginController {
    @Autowired
    private LoginService loginService;
    public  void  setLoginService(LoginService loginService){
        this.loginService=loginService;
    }

    @RequestMapping(value="/doLogin",method= {RequestMethod.POST})
    public String doLogin(LoginInfo loginInfo, HttpServletRequest request) {
        LoginInfo ok=loginService.login(loginInfo);
        if(ok!=null) {
            HttpSession session=request.getSession(true);
            session.setAttribute("currUser", ok);
            return "redirect:/main.jsp";
        }else {
            return "forward:/login.jsp?msg=no";
        }
    }
    @RequestMapping(value="/doReg",method= {RequestMethod.POST})
    public String doReg(LoginInfo loginInfo) {
            boolean bool=loginService.reregist(loginInfo);
            boolean bo=loginService.insel(loginInfo);
            System.out.println("============================================>>"+bool);
            if(bool&&bo) {
                return "forward:/login.jsp";
            }else {
                return "<script type=\"text/javascript\">alert('注册失败，请重新注册');location.href('register.jsp');</script>";
            }
    }
    @RequestMapping(value="/admin/doLogin2",method= {RequestMethod.POST})
    public String doLoginAdmin(LoginInfo loginInfo, ModelMap modelMap, HttpServletRequest request) {
        LoginInfo ok=loginService.loginAdmin(loginInfo);
        if(ok!=null) {
            HttpSession session=request.getSession(true);
            session.setAttribute("adminUser", ok);
            System.out.println("--------------->"+ok);
            return "admin/index";
        }else {
            modelMap.put("msg","no");
            return "admin/adminLogin";
        }
    }
    @RequestMapping(value = "doSel",method = {RequestMethod.GET,RequestMethod.POST},produces= {"application/JSON;charset=utf-8"})
    @ResponseBody
    public Object doSelect(@RequestParam String username, HttpServletRequest request){
        System.out.println(username);
        List<LoginInfo> list = loginService.selectLogin(username);
        JSONObject jsonObject = new JSONObject();
        if(list.size()==0){
            return JSON.toJSONString(null);
        }
        return JSON.toJSONString(list.get(0));
    }
}
